<template>
  <div class="main">
    <div>
      <div class="login-tab" :style="{justifyContent: isZw ? 'center' : 'space-between'}">
        <div @click="active = 0;showLoginCode=false" :class="[active == 0 ? 'active' : '']" v-if="!isZw">扫码登录</div>
        <div @click="active = 1;showLoginCode=false" :class="[active == 1 ? 'active' : '']">账号登陆</div>
      </div>
      <div class="login-btn-bg" style="margin-top: 30px" v-if="active == 1">
        <a-form-model ref="form" class="user-layout-login" :model="model" :rules="validatorRules">

          <a-form-model-item prop="username">
            <a-input v-model="model.username" size="large" placeholder="请输入您的账号">
              <a-icon slot="prefix" type="user" :style="{ color: '#1F3B8A', fontSize: '18px', marginRight: '24px' }"/>
            </a-input>
          </a-form-model-item>
          <a-form-model-item prop="password">
            <a-input v-model="model.password" size="large" type="password" autocomplete="false" placeholder="请输入您的密码">
              <a-icon slot="prefix" type="lock" :style="{ color: '#1F3B8A', fontSize: '18px', marginRight: '24px' }"/>
            </a-input>
          </a-form-model-item>
          <a-form-model-item prop="code" v-if="!isZw">
            <div style="display: flex;justify-content: space-between;width: 100%">
              <a-input style="width: 180px" :maxLength="6" v-model="model.code" size="large" placeholder="请输入短信验证码">

              </a-input>
              <a-button type="primary" @click="getCode" v-if="time === 0">发送短信</a-button>
              <a-button type="primary" disabled v-else>{{ time }}s后重新获取</a-button>
            </div>
          </a-form-model-item>
          <a-form-model-item prop="userCaptcha">
            <div style="display: flex;justify-content: space-between;width: 100%">
              <a-input style="width: 180px" v-model="model.userCaptcha" size="large" placeholder="请输入验证码">
              <!-- <a-icon slot="prefix" type="user" :style="{ color: '#1F3B8A', fontSize: '18px', marginRight: '24px' }"/> -->
              </a-input>
              <img style="cursor: pointer" v-if="refreshImg" :src="getCheckNumber" @click="refreshImgFun" alt="">
            </div>
          </a-form-model-item>

          <a-form-item style="margin-top: 28px">
            <a-button
              size="large"
              type="primary"
              class="login-button"
              shape="round"
              style="padding-top: 24px;padding-bottom: 24px;line-height: 0.1;"
              block
              :loading="loginBtn"
              @click.stop.prevent="handleSubmit">确定
            </a-button>
          </a-form-item>
        </a-form-model>
      </div>
      <div class="login-btn-bg" v-else-if="active == 0">
        <VuePictureVerify
          v-if="!showLoginCode"
          :show="showCode"
          :imgList="imgList"
          @success="showLoginCode = true"
        ></VuePictureVerify>
        <div class="login-code" v-else>
          <div class="iframe-bg">
            <iframe class="login-code--img" :src="url" frameborder="0" width="360px" height="360px"></iframe>
          </div>
          <p>使用<strong>浙政钉</strong>扫码登录 </p>
        </div>
      </div>
    </div>
    <a-modal v-model="show" title="绑定账号" @ok="search" onText="查询">
      <a-form-model ref="ruleform" class="user-layout-login" :model="form" :rules="rules">
        <a-form-model-item prop="mobile" label="手机号">
          <a-input v-model="form.mobile" size="large" placeholder="请输入您的手机号">

          </a-input>
          <div class="red" v-if="showerror">您的手机号没查到可绑定的账号,请联系相关人员下发账号!</div>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <a-modal v-model="showPhone" title="验证手机号" :footer="null">
      <div style="display: flex;justify-content: space-between;width: 100%">
        <a-input style="width: 70%" v-model="model.userCaptcha" placeholder="请输入短信验证码">
          <!-- <a-icon slot="prefix" type="user" :style="{ color: '#1F3B8A', fontSize: '18px', marginRight: '24px' }"/> -->
        </a-input>
        <a-button type="primary" @click="getCode" v-if="time === 0">发送短信</a-button>
        <a-button type="primary" disabled v-else>{{ time }}s后重新获取</a-button>
      </div>
    </a-modal>

    <a-modal
      :visible="showPwd"
      :width="880"
      title="修改密码"
      @cancel="showPwd = false"
      @ok="handleConfirm"
    >
      <a-form-model
        ref="ruleForm1"
        :model="pwdForm"
        :rules="pwdRule"
        style="margin-bottom:20px"
        v-bind="formItemLayout">
        <a-form-model-item label="原密码" prop="oldpassword">
          <a-input
            v-model="pwdForm.oldpassword"></a-input>
        </a-form-model-item>
        <a-form-model-item label="新密码" prop="password">
          <a-input v-model="pwdForm.password"></a-input>
        </a-form-model-item>
        <a-form-model-item label="确认新密码" prop="confirmpassword">
          <a-input
            v-model="pwdForm.confirmpassword"></a-input>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
// eslint-disable-next-line no-unused-vars
import { login, ddLogin, loginMobile, getUidByMobile, getCheckNumber, getCheckNumber2, getCode, updateUserPassword } from '@/api/user';
import { ACCESS_TOKEN, USERINFO } from '@/store/mutation-types';
import { v4 } from 'uuid';
import { AESEncrypt } from '@/utils/utils';
import imgList from '@/assets/imgList';
import { mapState } from 'vuex';

const reg = /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]{8,16}$/;

export default {
    components: {
    },
    computed: {
      ...mapState({
        userInfo: (state) => state.user.userInfo
      })
    },
    data() {
      const that = this;
      function validator(rule, value, callback) {
          if (!value) {
              callback(new Error('新密码不能为空！'));
          } else if (!reg.test(value)) {
              callback(new Error('密码必须8-16位且包含数字，大写字母，小写字母，特殊字符中的任意三种！'));
          } else {
              callback();
          }
      }
      function validatorConfirm(rule, value, callback) {
          if (!value) {
              callback(new Error('密码不能为空！'));
          } else if (that.pwdForm.password != value) {
              callback(new Error('密码不一致！！'));
          } else {
              callback();
          }
      }
      return {
        showPwd: false,
        pwdForm: {},
        formItemLayout: {
          labelCol: {
            xs: { span: 24 },
            sm: { span: 6 }
          },
          wrapperCol: {
            xs: { span: 24 },
            sm: { span: 14 }
          }
        },
        pwdRule: {
          oldpassword: [{ required: true, message: '旧密码不能为空' }],
          password: [{ required: true, validator }],
          confirmpassword: [{ required: true, validator: validatorConfirm }]
        },

        showLoginCode: false,
        imgList,
        active: 1,
        showPhone: false,
        showCode: true,
        code: '',
        checkKey: '',
        time: 0,
        show: false,
        showerror: false,
        isZw: process.env.VUE_APP_TYPE == 2 || process.env.NODE_ENV == 'development',
        refreshImg: true,
        form: {},
        getCheckNumber: '',
        // https://login.dg-work.cn/oauth2/auth.htm?response_type=code&client_id=应用标识&redirect_uri=回调地址&scope=get_user_info&authType=QRCODE&embedMode=true wxb_login_zzd_dingoa wxb_login_dingoa
        url: `https://login-pro.ding.zj.gov.cn/oauth2/auth.htm?response_type=code&client_id=ywzx_ding_dingoa&redirect_uri=${encodeURIComponent(window.location.protocol + '//' + window.location.host)}&scope=get_user_info&authType=QRCODE&embedMode=true`,
        customActiveKey: 'tab1',
        rememberMe: true,
        loginBtn: false,
        requiredTwoStepCaptcha: false,
        stepCaptchaVisible: false,
        encryptedString: {
          key: '',
          iv: ''
        },
        model: {
          username: 'test_01',
          password: 'wxb123!@#'
        },
        validatorRules: {
          username: [
            { required: true, message: '请输入用户名!' }
          ],
          password: [{
            required: true, message: '请输入密码!'
          }],
          userCaptcha: [{
            required: true, message: '请输入验证码!'
          }],
          code: [{
            required: true, message: '请输入短信验证码!'
          }]
        },
        rules: {
          mobile: [
            { required: true, message: '请输入手机号!' }
          ]
        },
        requestCodeSuccess: false,
        accountId: ''
      };
    },
    created() {
      const that = this;
      this.refreshImgFun();
      window.onmessage = function(event) {
        console.log(event.data, 'event data');
        if (event.data && event.data.code) {
          if (process.env.VUE_APP_TITLE == 'test') {
            that.$info({
              content: `code: ${event.data.code}`
            });
            return;
          }
          // eslint-disable-next-line no-unreachable
          ddLogin({ code: event.data.code }).then(res => {
            if (!res.data.token) {
              that.show = true;
              that.accountId = res.data.accountId;
              that.$message.error(res.data.title);
            } else {
              that.$notification.success({
                message: '登录成功',
                description: res.msg
              });
              that.$ls.set(ACCESS_TOKEN, res.data.token);

              that.$store.dispatch('UserInfo', res.data).then(() => {
                that.$router.push('/');
              });
            }
          });
        }
        // alert(JSON.stringify(event.data));
      };
    },
    methods: {
        refreshImgFun() {
          this.checkKey = `${v4()}`;
          this.getCheckNumber = getCheckNumber() + '?checkKey=' + encodeURIComponent(AESEncrypt(this.checkKey)) + '&v=' + new Date().getTime();

          // getCheckNumber2({
          //   checkKey: this.checkKey
          // }).then(res => {

          // });
        },
      getCode() {
        if (!this.model.username) {
          this.$message.error('请输入手机号！');
          return;
        }
        if (this.time !== 0) return;
        this.time = 60;
        const s = setInterval(() => {
          if (this.time === 0) {
            clearInterval(s);
            return;
          }
          this.time -= 1;
        }, 1000);
        getCode({
          mobile: this.model.username
        }).then(res => {

        }).catch(() => {
          clearInterval(s);
          this.time = 0;
        });
      },
      // 登录
      handleSubmit() {
        this.$refs.form.validate(valid => {
          if (valid) {
            // this.loginBtn = true;
            const { username, password, userCaptcha, code } = this.model;
            console.log({ username, password, userCaptcha });
            const form = {
              username: AESEncrypt(username),
              password: AESEncrypt(password),
              userCaptcha: AESEncrypt(userCaptcha),
              checkKey: AESEncrypt(this.checkKey)
            };
            if (!this.isZw) {
              form.code = AESEncrypt(code);
            }
            login(form).then(res => {
              console.log(res.data);
              this.show = false;
              this.$notification.success({
                message: '登录成功',
                description: res.msg
              });
              this.$ls.set(ACCESS_TOKEN, res.data.token);

              this.$store.dispatch('UserInfo', res.data).then(() => {
                this.$router.push('/');
              });
            }).catch((err) => {
              console.log(err);
              if (err.code == 999999) {
                this.refreshImgFun();
              }
              if (err.code === 0 && err.msg == '您的密码超过90天未做修改，现要求您强制更换新密码') {
                this.$store.dispatch('UserInfo', err.data).then(() => {

                });
                this.$message.error(err.msg);
                this.$ls.set(ACCESS_TOKEN, err.data.token);
                this.showPwd = true;
              }
              // this.loginBtn = false;
            });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      search() {
        const that = this;
        this.$refs.ruleform.validate(valid => {
          if (valid) {
            // this.loginBtn = true;
            getUidByMobile({
              ...this.form
            }).then(res => {
              if (res.data.uid) {
                this.showerror = false;
                this.$ls.set(USERINFO, res.data);
                this.$confirm({
                  content: '是否绑定手机号？',
                  onOk() {
                    that.submit();
                  }
                });
              } else {
                this.showerror = true;
              }
            }).catch(() => {
              // this.loginBtn = false;
            });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      submit() {
        this.$refs.ruleform.validate(valid => {
          if (valid) {
            this.loginBtn = true;
            loginMobile({
              ...this.form,
              accountId: this.accountId
            }).then(res => {
              this.$notification.success({
                message: '登录成功',
                description: res.msg
              });
              this.$ls.set(ACCESS_TOKEN, res.data.token);

              this.$store.dispatch('UserInfo', res.data).then(() => {
                this.$router.push('/');
              });
            }).catch((res) => {
              this.loginBtn = false;
            });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      handleConfirm() {
        this.$refs.ruleForm1.validate((valid) => {
          if (valid) {
            if (this.pwdForm.password !== this.pwdForm.confirmpassword) {
                this.$message.error('两次密码输入不一致');
            } else {
              console.log(this.userInfo);
              updateUserPassword({
                  username: this.userInfo.username,
                  password: this.pwdForm.password,
                  oldPassword: this.pwdForm.oldpassword,
                  id: this.userInfo.uid
              }).then(res => {
                  this.$message.success(res.msg);
                  this.pwdForm.password = '';
                  this.pwdForm.confirmpassword = '';
                  this.pwdForm.oldpassword = '';
                  this.$nextTick(() => {
                      this.$refs['ruleForm1'].clearValidate();
                  });
                  this.showPwd = false;

                  this.refreshImgFun();
                  // this.model.username = '';
                  this.model.password = '';
                  this.model.code = '';
                  this.model.userCaptcha = '';
                  this.time = 0;
              });
            }
          }
        });
      }

    }

  };
</script>
<style lang="less">

  .main {

    // display: flex;
    // align-items: center;
    // height: inherit;
    color: #333;
    .ant-input-affix-wrapper .ant-input:not(:first-child) {
      padding-left: 48px;
    }
    p,h1 {
      margin: 0;
    }
    .ant-input {
      border: none;
      border-bottom: 1px solid #d9d9d9;
      border-radius: 0;
      &:focus,&:hover {
        border: none !important;
        border-bottom: 1px solid #395596 !important;
        box-shadow: none !important;
      }
    }
    .login-icon {
      width: 370px;
      margin-left: 16px;
    }
    .login-code {
      // margin-left: 65px;
      text-align: center;
      // margin-right: 78px;
      // border-right: 1px solid #f1f1f1;
      // padding-right: 60px;
      margin: 0 auto;
      margin-top: -50px;
      h1 {
        font-size: 20px;
        font-weight: 400;
        color: #333333;
        margin-bottom: 24px;
        font-weight: 500;
        letter-spacing: 0.05em;
      }
      .login-code--img {
        width: 300px;
        height: 300px;
        // border: 1px solid #ddd;
        margin: 0 auto;
        transform: translate(-45px, -85px);
      }
      .iframe-bg {
        width: 200px;
        height: 200px;
        overflow: hidden;
        margin: 0 auto;
      }
      p {
        font-size: 14px;
        font-weight: 400;
        color: #999999;
        line-height: 35px;
        margin-top: 8px;
        text-align: center;
      }
    }
    .login--form {
      height: 400px;
      >h1 {
        font-size: 20px;
        font-size: 500;
        text-align: center;
        margin-bottom: 100px;
      }
      .ant-form-item {
        margin-bottom: 24px !important;
      }
      .ant-input-affix-wrapper .ant-input:not(:first-child) {
        padding-left: 40px;
      }
    }
    .user-layout-login {
      margin: 0 auto;
      width: 100%;
    }
  }

  .login-tab {
    display: flex;
    width: 92%;
    justify-content: space-between;
    margin: 0 auto;
    >div{
      font-size: 22px;
      font-family: Source Han Sans CN;
      font-weight: 400;
      color: #999;
      line-height: 58px;
      cursor: pointer;
      &.active {
        color: #333;
      }
    }
  }

  .login-btn-bg {
    margin-top: 80px;
  }
</style>
<style>
  .valid-error .ant-select-selection__placeholder{
    color: #f5222d;
  }
  .slider-main {
    cursor: move;
  }
</style>
